<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\model\Account as AccountModel;
use app\common\tool\account\Account;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

class BonusPool extends Base
{
    protected $name = 'bonus_pool';

    public static $_type = [
        '1' => '店主',
        '2' => '盟主',
        '3' => '区代',
        '4' => '市代'
    ];

    public function getTypeTextAttr($value, $data)
    {
        return isset(self::$_type[$data['type']]) ? self::$_type[$data['type']] : '';
    }

    public static function _save($param, $admin): array
    {
        parent::startTrans();
        try {
            $info = parent::where('id', $param['id'])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '记录不存在'];
            }

            if($info->actual_amount != $param['actual_amount']){
                BonusPoolEditLog::create([
                    'pool_id' => $info->id,
                    'old_amount' => $info->actual_amount,
                    'new_amount' => $param['actual_amount'],
                    'admin_id' => $admin['id'],
                    'admin_name' => $admin['admin_name'],
                    'create_time' => time()
                ]);
                $info->actual_amount = $param['actual_amount'];
                $info->save();
            }

            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 清空店主分红池：  每周一凌晨00:05执行
     * @return array
     */
    public static function clearShoperPool()
    {
        return self::clear(1);
    }

    /**
     * 清空分盟主、区代、市代红池  每月25号凌晨00:05执行
     * @return array
     */
    public static function clearPool()
    {
        return self::clear(2);
    }

    private static function clear($type=1)
    {
        parent::startTrans();
        try{
            $query = 1 == $type ? BonusPool::where('type',1) : BonusPool::where('type','<>',1);
            $query->select()->each(function ($item){
                BonusPoolEditLog::create([
                    'pool_id' => $item->id,
                    'old_amount' => $item->total_amount,
                    'new_amount' => 0,
                    'create_time' => time(),
                    'type' => 2
                ]);
                $item->actual_amount = $item->total_amount;
                $item->total_amount = 0;
                $item->save();
            });
            if(2 == $type) {
                User::where('is_del', 0)->select()->each(function ($item){
                    $item->my_leader_lastm = $item->my_leader_currm;
                    $item->team_three_lastm = $item->team_three_currm;
                    $item->my_leader_currm = 0;
                    $item->team_three_currm = 0;
                    $item->save();
                });
            }

            parent::commit();
        }catch (\Exception $e){
            parent::rollback();
            Log::write("分红池清空执行失败clear：".$e->getMessage());
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '分红池清空执行成功'];
    }

    /**
     * 每周一上午10点执行
     * 店主分红
     */
    public static function shoperBonus()
    {
        try {
            $bonus = BonusPool::where('type',1)->limit(1)->value('actual_amount');
            if($bonus<=0){
                return ['code' => -1, 'msg' => '店主分红池暂无可分奖励'];
            }
            $countQuery = User::whereIn('level_id',[3,4]);

            $count1 = $countQuery->where('my_total','>=',20000)->count();
            if($count1 == 0){
                return ['code' => -1, 'msg' => '店主分红池暂无可分奖励的店主'];
            }
            $count2 = $countQuery->where('my_total','>=',40000)->count();
            $count3 = $countQuery->where('my_total','>=',60000)->count();
            $count4 = $countQuery->where('my_total','>=',80000)->count();
            $count5 = $countQuery->where('my_total','>=',100000)->count();


            $every1 = $count1 > 0 ? roundNum($bonus/$count1) : 0;
            $every2 = $count2 > 0 ? roundNum($bonus/$count2) : 0;
            $every3 = $count3 > 0 ? roundNum($bonus/$count3) : 0;
            $every4 = $count4 > 0 ? roundNum($bonus/$count4) : 0;
            $every5 = $count5 > 0 ? roundNum($bonus/$count5) : 0;

            User::whereIn('level_id',[3,4])->where('my_total','>=',20000)->field('id,mobile,level_id,my_total')->select()->each(function ($item) use ($every1,$every2,$every3,$every4,$every5){
                $cate = AccountModel::CONSUM_SHARE_SHOPER;
                if($every1 > 0){
                    Account::getInstance()->basics($item->id, 'love_bean', $every1 , "店主分红池分红[店主消费满20000]", '+')->createBonus(0,$cate);
                }

                if($item->my_total >= 40000 && $every2>0){
                    Account::getInstance()->basics($item->id, 'love_bean', $every2 , "店主分红池分红[店主消费满40000]", '+')->createBonus(0,$cate);
                }
                if($item->my_total >= 60000 && $every3>0){
                    Account::getInstance()->basics($item->id, 'love_bean', $every3 , "店主分红池分红[店主消费满60000]", '+')->createBonus(0,$cate);
                }
                if($item->my_total >= 80000 && $every4>0){
                    Account::getInstance()->basics($item->id, 'love_bean', $every4 , "店主分红池分红[店主消费满80000]", '+')->createBonus(0,$cate);
                }
                if($item->my_total >= 100000 && $every5>0){
                    Account::getInstance()->basics($item->id, 'love_bean', $every5 , "店主分红池分红[店主消费满100000]", '+')->createBonus(0,$cate);
                }
            });

            BonusPool::where('type',1)->save(['actual_amount'=>0]);
        }catch (\Exception $e){
            Log::write("shopkeeperBonus失败>>".$e->getMessage());
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
        return ['code' => 1, 'msg' => '店主分红执行成功'];
    }

    public static function poolBonus()
    {
        try {
            self::leaderBonus();
            self::cityDistrictBonus(1);
            self::cityDistrictBonus(2);

            BonusPool::whereIn('type',[2,3,4])->save(['actual_amount'=>0]);
        }catch (\Exception $e){
            Log::write("poolBonus失败>>".$e->getMessage());
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
        return ['code' => 1, 'msg' => '盟主、市代、区代分红执行成功'];
    }

    private static function leaderBonus()
    {
        $bonus = BonusPool::where('type',2)->value('actual_amount');
        if($bonus<=0){
            return false;
        }

        if(confValue('pool_ldc_open')){
            $leader_repeat_amount = confValue('leader_repeat_amount');
            $leader_team_three_amount = confValue('leader_team_three_amount');
        }else{
            $leader_repeat_amount = $leader_team_three_amount = 0;
        }

        $uids = User::where('level_id', 5)->where('level_bonus_id','>',0)->where('my_leader_lastm','>=',$leader_repeat_amount)->where('team_three_lastm','>=',$leader_team_three_amount)->column('level_bonus_id','id');
        if($uids){
            $all_levels = UserLevelBonus::column('weight','id');
            $ac = array_count_values($uids);
            $total_weight = 0;
            foreach($ac as $key=>$val){
                $total_weight += $all_levels[$key]*$val;
            }

            if($total_weight > 0){
                User::whereIn('id',array_keys($uids))->select()->each(function ($item) use ($total_weight,$bonus,$all_levels){
                    $amount = roundNum($bonus*($all_levels[$item->level_bonus_id])/$total_weight, 2);
                    Account::getInstance()->basics($item->id, 'love_bean', $amount , "盟主分红池分红", '+')->createBonus(0,AccountModel::CONSUM_SHARE_LEADER);
                });
            }
        }

        return true;

    }

    private static function cityDistrictBonus($flag = 1)
    {
        if($flag == 1){
            $pool_type = 4;
            $area_level = 2;
            $repeat_amount = confValue('city_repeat_amount');
            $team_three_amount = confValue('city_team_three_amount');
            $note = "市代分红池分红";
            $cate = AccountModel::CONSUM_SHARE_CITY;
        }else{
            $pool_type = 3;
            $area_level = 3;
            $repeat_amount = confValue('district_repeat_amount');
            $team_three_amount = confValue('district_team_three_amount');
            $note = "区代分红池分红";
            $cate = AccountModel::CONSUM_SHARE_DISTRICT;
        }

        if(!confValue('pool_ldc_open')){
            $repeat_amount = $team_three_amount = 0;
        }
        if($bonus = BonusPool::where('type',$pool_type)->value('actual_amount')){
            //if($uids = Area::where('level',$area_level)->where('uid','>',0)->column('uid')){
            //    $userQuery = User::whereIn('id',$uids)->where('my_leader_total','>=',$repeat_amount)->where('team_three_total','>=',$team_three_amount);
            //    if($count = $userQuery->count()){
            //        $every = roundNum($bonus/$count,2);
            //        $userQuery->select()->each(function ($item) use ($every,$note,$cate){
            //            Account::getInstance()->basics($item->id, 'love_bean', $every , $note, '+')->createBonus(0,$cate);
            //        });
            //    }
            //
            //}

            if(2 == $area_level){
                $agent = [2,3];
            }else{
                $agent = [1,3];
            }
            if($uids = User::whereIn('agent_level', $agent)->where('my_leader_lastm','>=',$repeat_amount)->where('team_three_lastm','>=',$team_three_amount)->column('id')){
                $areaQuery = Area::where('level', $area_level)->whereIn('uid', $uids);
                if($count = $areaQuery->count()){
                    $every = roundNum($bonus/$count,2);
                    $areaQuery->select()->each(function ($item) use ($every,$note,$cate){
                        Account::getInstance()->basics($item->uid, 'love_bean', $every , $note, '+')->createBonus(0,$cate);
                    });
                }
            }

        }

        return true;

    }

}
